<?php
namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class PhoneController extends Controller
{
    /**
     * @var array
     * 电话类型
     * 1:PSTN电话,2:SIP网关,5:SIP远程分机
     */
    protected $phonType = array('1'=>'PSTN电话','2'=>'SIP网关','5'=>'SIP远程分机');

    /**
     * @param Request $request
     * @return JsonResponse
     * 添加分机号
     */
    public function addAction(Request $request)
    {
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code = $request->get('vcc_code', 0);
        $pho_type = $request->get('pho_type', '');


        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        if (!in_array($pho_type, array_keys($this->phonType))) {
            return new JsonResponse(array('code'=>403,'message'=>'电话类型值有误(1,2,5)'));
        }

        switch ($pho_type)
        {
            //sip,pstn
            case 1:
            case 2:
                $pho_num = $request->get('pho_num', '');
                if (empty($pho_num)) {
                    return new JsonResponse(array('code'=>404,'message'=>'电话号码为空'));
                }
                $phones = json_decode($pho_num);
                if (json_last_error() || !is_array($phones)) {
                    return new JsonResponse(array('code'=>405,'message'=>'pho_num格式不正确'));
                }
                foreach ($phones as $phone_item) {
                    if (is_numeric($phone_item)) {
                        //判断分机数据库中是否已经存在
                        $if_exit_query = $conn->fetchColumn(
                            'SELECT COUNT(*) '.
                            'FROM win_phone '.
                            'WHERE vcc_id = :vcc_id AND pho_num = :pho_num ',
                            array('vcc_id'=>$vid, 'pho_num'=>$phone_item)
                        );
                        if ($if_exit_query > 0) {
                            continue;
                        }
                        $phone_info = array(
                            'pho_num' => $phone_item,
                            'pho_type' => $pho_type,
                            'vcc_id' => $vid
                        );
                        $conn->insert('win_phone', $phone_info);
                    }
                }
                break;
            case 5:
                //sip远程分机
                $pho_start = $request->get('pho_start', '');
                $pho_end = $request->get('pho_end', '');
                $pass_type = $request->get('passtype', 1);
                $pho_pass = $request->get('pho_pass', '');
                if (empty($pho_start) || !preg_match("/\d{4}/", $pho_start)) {
                    return new JsonResponse(array('code'=>406,'message'=>'开始分机号格式有误'));
                }
                if (!empty($pho_end)) {
                    if (!preg_match("/\d{4}/", $pho_end)) {
                        return new JsonResponse(array('code'=>407,'message'=>'结束分机号格式有误'));
                    }
                } else {
                    $pho_end = $pho_start;
                }
                for ($i = $pho_start; $i <= $pho_end; $i++) {
                    $if_exit_query = $conn->fetchColumn(
                        'SELECT COUNT(*) '.
                        'FROM win_phone '.
                        'WHERE vcc_id = :vcc_id AND pho_num = :pho_num ',
                        array('vcc_id'=>$vid, 'pho_num'=>$i)
                    );
                    if ($if_exit_query > 0) {
                        continue;
                    }
                    $data = array();
                    $data['pho_num'] = $i;
                    if ($pass_type == 1 || empty($pho_pass)) {
                        $data['pho_pass'] = $this->get('help.function')->randString() ;
                    } else {
                        $data['pho_pass'] = $pho_pass;
                    }
                    $data['vcc_id'] = $vid;
                    $data['pho_type'] = $pho_type;
                    $conn->insert('win_phone', $data);
                }
                break;
        }
        return new JsonResponse(array('code'=>200, 'message'=>'ok'));
    }

    /**
     * @param $vcc_code
     * @param $ids
     * @return JsonResponse
     * 删除分机号
     */
    public function deleteAction($vcc_code, $ids)
    {
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");

        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        $arr = json_decode($ids);
        if (json_last_error() || !is_array($arr) || empty($arr)) {
            return new JsonResponse(array('code'=>403,'message'=>'ids格式不正确'));
        }

        //转整
        $temp = $msg = array();
        foreach ($arr as $v) {
            $value = (int)$v;
            if ($value == 0) {
                continue;
            }
            //查看是否被坐席占用
            $count = $conn->fetchColumn(
                "SELECT count(*) FROM win_agent WHERE ag_type = 2 AND pho_id = :pid",
                array('pid' => $value)
            );
            if ($count > 0) {
                $msg[] = $value;
                continue;
            }
            $temp[] = $value;
        }
        $temp = array_unique($temp);
        $str = implode(',', $temp);
        $conn->executeQuery("DELETE FROM win_phone WHERE vcc_id = :vid AND id IN ($str)", array('vid'=>$vid));
        return new JsonResponse(array('code'=>500, 'message'=>'总结果', 'data'=>array('success'=>$temp, 'fail'=>$msg)));
    }

    public function listAction(Request $request)
    {
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code = $request->get('vcc_code', 0);
        $info = $request->get('info', ''); //分页搜索相关信息；

        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        $addInfo = array(); //分页搜索相关信息；
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error() || !is_array($addInfo)) {
                return new JsonResponse(array('code' => 403, 'message'=>'info格式非json'));
            }
        }

        $where = '';
        if (isset($addInfo['filter'])) {
            $where = isset($addInfo['filter']['phone']) && !empty($addInfo['filter']['phone']) ?
                " AND pho_num LIKE '%".$addInfo['filter']['phone']."%' " : '';
        }

        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_phone '.
            'WHERE vcc_id = :vid '.$where,
            array('vid'=>$vid)
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_phone', $addInfo);
        $list = $conn->fetchAll(
            'SELECT id,pho_num,pho_type,pho_pass '.
            'FROM win_phone '.
            'WHERE vcc_id = :vid '.$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            array('vid'=>$vid)
        );
        $data = array();
        foreach ($list as $v) {
            $v['type_msg'] = isset($this->phonType[$v['pho_type']]) ? $this->phonType[$v['pho_type']] : '未设置';
            $data[] = $v;
        }
        $ret = array(
            'code' => 200,
            'message' =>'ok',
            'total' => $count,
            'data' => $data,
        );
        return new JsonResponse($ret);
    }
}
